/**
 * @description:
 * @param {string} key
 * @param {object} value
 * @param {any} expire：过期时间
 * @return {*}https://www.csdn.net/tags/MtTacgzsMTg0NDAtYmxvZwO0O0OO0O0O.html
 */
export const setItem = (key: string, value: object | string | null, expire: any) => {
  if (typeof value === 'object') {
    // 对象转字符串 JSON.stringify
    value = JSON.stringify(value)
  }
  const obj = {
    data: value,
    time: Date.now(),
    expire: 1000 * 60 * expire // 单位是分钟
  }
  window.localStorage.setItem(key, JSON.stringify(obj))
}

/**
 * @description:判断key是否过期
 * @param {*} T
 * @return {*}
 */
export const getItem = <T>(key: string): T | null => {
  const value = JSON.parse(window.localStorage.getItem(key)||'0').data
  if (!value) return null
  try {
    const storageInfo = JSON.parse(value)
    const timeSpan = Date.now() - storageInfo.time
    if (timeSpan > storageInfo.expire) {
      removeItem(key)
      return null
    }
    return storageInfo as T
  } catch (err) {
    return null
  }
}

/**
 * @description:
 * @param {string} key
 * @return {*}
 */
export const removeItem = (key: string) => {
  window.localStorage.removeItem(key)
  console.log('hhh')
}
